//
//  UpImageTools.m
//  LoveLove
//
//  Created by leiyifan on 2019/5/25.
//  Copyright © 2019 wkf. All rights reserved.
//

#import "UpImageTools.h"
#import "AliyunOSSiOS.h"


@implementation UpImageTools

#define AccessKeyId @"LTAIhA7zAsm3QW3a"
#define SecretKeyId @"32lzQfA2Q9ITGt1qTaLjuZqMESclCM"
#define BucketName @"haoaihao"
#define Endpoint @"https://oss-cn-beijing.aliyuncs.com"
/// 上传回调
typedef void(^uploadCallblock)(BOOL success, NSString* msg, NSArray<NSString *>* keys);

//阿里云图片上传
+(void)upLoadImage:(UIImage*)image success:(void(^)(NSString*_Nonnull url))success failure:(void(^)(NSString*_Nonnull errorString))failure{  //    将image转成Data
//    [self showAlertViewWithMessage:@"正在上传图片。。。"];
    LLUserInfo *user = [LLUserInfo sharedUser];
    NSData *data = UIImageJPEGRepresentation(image, 0.7);
    NSString *endpoint = Endpoint;//去阿里云控制台查看    //AccessKeyId --- secretKeyId 去阿里云控制台查看  securityToken填空字符串就好了
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKeyId secretKeyId:SecretKeyId securityToken:@""];
    OSSClient*client = [[OSSClient alloc]initWithEndpoint:endpoint credentialProvider:credential];
        OSSPutObjectRequest *put = [OSSPutObjectRequest new];
      put.bucketName = BucketName;//去阿里云控制台查看    //根据用户ID和时间戳来生成一段字符串 来保证图片的唯一性
    NSString *timestr = [NSString stringWithFormat:@"%@%@",user.user_id,[self getGMTDate]];// 其中test/是bucket下的子文件夹路径，可以根据路径上传到指定文件夹
    put.objectKey= [NSString stringWithFormat:@"%@.jpg",timestr];
    //设置上传文件格式（告诉浏览器这是图片，不然默认的是下载）
    put.contentType = @"image/jpeg";
    put.uploadingData= data;// 直接上传NSData
//    put.uploadProgress = ^(int64_tbytesSent,int64_ttotalByteSent,int64_ttotalBytesExpectedToSend) {
//        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
//        };
    OSSTask * putTask = [client putObject:put];
     [SVProgressHUD showWithStatus:@"正在上传图片..."];
    [putTask continueWithBlock:^id(OSSTask*task) { //这一步很关键 缺少这一步运行会出错   里面的参数和上面一样
        [SVProgressHUD dismiss];
         task = [client presignPublicURLWithBucketName:BucketName withObjectKey:[NSString stringWithFormat:@"%@.jpg",timestr]];
        NSLog(@"objectkey ======%@",put.objectKey);
        if(!task.error) { //task.result就是返回的外网访问路径，即图片URL
             success(task.result);
             }else{
                 NSLog(@"upload object failed, error: %@" , task.error); failure(task.error.localizedDescription);
                  }
            return nil;
        }];}


//阿里云视频上传
+ (void)asyncUploadVideo:(NSString *)filePath success:(void(^)(NSString*_Nonnull url))success failure:(void(^)(NSString*_Nonnull errorString))failure{
    
     LLUserInfo *user = [LLUserInfo sharedUser];
//     NSString *endpoint = Endpoint;//去阿里云控制台查看
    id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:AccessKeyId secretKeyId:SecretKeyId securityToken:@""];
    OSSClient*client = [[OSSClient alloc]initWithEndpoint:Endpoint credentialProvider:credential];
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // 必填字段
    put.bucketName = BucketName;
    NSString *timestr = [NSString stringWithFormat:@"%@",[self getGMTDate]];// 其中test/是bucket下的子文件夹路径，可以根据路径上传到指定文件夹
    put.objectKey =[NSString stringWithFormat:@"%@.mp4",timestr];
    put.uploadingFileURL = [NSURL fileURLWithPath:filePath];
    put.contentType = @"video/mpeg4";
    // put.uploadingData = <NSData *>; // 直接上传NSData
    // 可选字段，可不设置
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {

        // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
//        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
        float percent = totalByteSent/1.0f/totalBytesExpectedToSend;
        NSLog(@"%.2f",percent);
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
        [SVProgressHUD showProgress:percent status:@"正在上传。。。"];
       
    };
    // 以下可选字段的含义参考： https://docs.aliyun.com/#/pub/oss/api-reference/object&PutObject
    // put.contentType = @"";
    // put.contentMd5 = @"";
    // put.contentEncoding = @"";
    // put.contentDisposition = @"";
    // put.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil]; // 可以在上传时设置元信息或者其他HTTP头部
    OSSTask * putTask = [client putObject:put];
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [SVProgressHUD showWithStatus:@"正在上传视频..."];
//    });
  
    [putTask continueWithBlock:^id(OSSTask *task) {
        dispatch_async(dispatch_get_main_queue(), ^{
             [SVProgressHUD dismiss];
        });
        if (!task.error) {
            NSLog(@"upload object success!");
//            https://haoaihao.oss-cn-beijing.aliyuncs.com/1559033289.mp4
            NSString *videoUrl = [NSString stringWithFormat:@"https://%@.oss-cn-beijing.aliyuncs.com/%@.mp4",BucketName,timestr];
            success(videoUrl);
            
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
            failure(task.error.localizedDescription);
        }
        return nil;
    }];
     [putTask waitUntilFinished];
}
+ (NSString*) getGMTDate{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    return timeString;
    
}

@end
